<script setup lang="ts">
import { ref, onMounted, provide } from 'vue';
import HarUploader from './components/HarUploader.vue';
import HarViewer from './components/HarViewer.vue';
import Comparison from './components/Comparison.vue';
import PerformanceChart from './components/Charts/PerformanceChart.vue';
import { useHarStore } from './stores/harStore';
import type { HarFile, ComparisonResult } from './types/har';

// 使用状态管理
const harStore = useHarStore();

// 当前视图状态
const currentView = ref<'upload' | 'view' | 'compare'>('upload');
const selectedFile = ref<HarFile | null>(null);
const comparisonResult = ref<ComparisonResult | null>(null);

// 提供状态给子组件
provide('harStore', harStore);

// 方法
async function handleFilesUpdate(files: HarFile[]) {
  try {
    // 找出新增的文件
    const currentFiles = harStore.harFiles.value;
    const newFiles = files.filter(newFile => 
      !currentFiles.some(currentFile => currentFile.id === newFile.id)
    );
    
    console.log('Files update - Current:', currentFiles.length, 'New:', newFiles.length);
    
    if (newFiles.length > 0) {
      // 使用状态管理的 addFiles 方法保存到 IndexedDB
      console.log('Saving new files to IndexedDB:', newFiles.map(f => f.name));
      await harStore.addFiles(newFiles);
      console.log('Successfully saved files to IndexedDB');
    }
  } catch (error) {
    console.error('Failed to save files:', error);
  }
}

function handleFileSelected(file: HarFile) {
  selectedFile.value = file;
  currentView.value = 'view';
}

function handleFileRemoved(fileId: string) {
  if (selectedFile.value?.id === fileId) {
    selectedFile.value = null;
    currentView.value = 'upload';
  }
  // 使用状态管理的 removeFile 方法
  harStore.removeFile(fileId);
}

function handleComparisonCompleted(result: ComparisonResult) {
  comparisonResult.value = result;
  currentView.value = 'compare';
}

function switchView(view: 'upload' | 'view' | 'compare') {
  currentView.value = view;
}

// 生命周期
onMounted(async () => {
  console.log('App mounted, loading files from IndexedDB...');
  await harStore.loadFiles();
  console.log('Loaded files from IndexedDB:', harStore.harFiles.value.length);
});
</script>

<template>
  <div class="app">
    <!-- 顶部导航 -->
    <header class="app-header">
      <div class="header-content">
        <h1 class="app-title">HAR 性能分析工具</h1>
        <nav class="app-nav">
          <button 
            @click="switchView('upload')"
            :class="{ active: currentView === 'upload' }"
            class="nav-btn"
          >
            文件管理
          </button>
          <button 
            @click="switchView('view')"
            :class="{ active: currentView === 'view' }"
            :disabled="!selectedFile"
            class="nav-btn"
          >
            文件查看
          </button>
          <button 
            @click="switchView('compare')"
            :class="{ active: currentView === 'compare' }"
            :disabled="harStore.fileCount.value < 2"
            class="nav-btn"
          >
            对比分析
          </button>
        </nav>
      </div>
    </header>

    <!-- 主要内容区域 -->
    <main class="app-main">
      <!-- 文件管理视图 -->
      <div v-if="currentView === 'upload'" class="view-container">
        <div class="upload-view-content">
          <div class="view-header">
            <h2>HAR 文件管理</h2>
            <div class="file-stats" v-if="harStore.hasFiles">
              <span>已上传 {{ harStore.fileCount }} 个文件</span>
              <span>总大小: {{ formatFileSize(harStore.fileStats.value.totalSize) }}</span>
            </div>
          </div>
          <HarUploader 
            :model-value="harStore.harFiles.value"
            :selected-file="selectedFile"
            @update:model-value="handleFilesUpdate"
            @file-selected="handleFileSelected"
            @file-removed="handleFileRemoved"
          />
        </div>
      </div>

      <!-- 文件查看视图 -->
      <div v-if="currentView === 'view'" class="view-container">
        <div class="view-header">
          <h2>文件详情分析</h2>
          <div class="file-info" v-if="selectedFile">
            <span>{{ selectedFile.name }}</span>
            <span>{{ formatFileSize(selectedFile.size) }}</span>
          </div>
        </div>
        <div class="view-content">
          <div class="content-main">
            <HarViewer 
              :har-file="selectedFile"
              @request-selected="(entry) => console.log('Selected request:', entry)"
            />
          </div>
        </div>
      </div>

      <!-- 对比分析视图 -->
      <div v-if="currentView === 'compare'" class="view-container">
        <div class="view-header">
          <h2>性能对比分析</h2>
          <div class="file-info" v-if="harStore.fileCount.value >= 2">
            <span>已上传 {{ harStore.fileCount.value }} 个文件</span>
            <span>可选择任意两个文件进行对比</span>
          </div>
        </div>
        <div class="view-content">
          <div class="content-main">
            <Comparison 
              :files="harStore.harFiles.value"
              @comparison-completed="handleComparisonCompleted"
            />
          </div>
          <div class="content-sidebar" v-if="comparisonResult">
            <div class="chart-panel">
              <h3>性能对比图表</h3>
              <PerformanceChart 
                :baseline-metrics="comparisonResult.baseline.metrics"
                :target-metrics="comparisonResult.target.metrics"
                title="性能指标对比"
              />
            </div>
          </div>
        </div>
      </div>
    </main>

    <!-- 底部状态栏 -->
    <footer class="app-footer">
      <div class="footer-content">
        <span>HAR 性能分析工具 v1.0</span>
        <span v-if="harStore.isLoading">加载中...</span>
        <span v-if="harStore.error" class="error">{{ harStore.error }}</span>
      </div>
    </footer>
  </div>
</template>

<style scoped>
/* 全局变量 */
:root {
  --primary-color: #6366f1;
  --primary-hover: #4f46e5;
  --primary-light: #e0e7ff;
  --secondary-color: #475569;
  --success-color: #10b981;
  --warning-color: #f59e0b;
  --error-color: #ef4444;
  --background: #f8fafc;
  --surface: #ffffff;
  --surface-hover: #f1f5f9;
  --border: #e2e8f0;
  --border-light: #f1f5f9;
  --text-primary: #000000;
  --text-secondary: #1e293b;
  --text-muted: #334155;
  --shadow-sm: 0 1px 2px 0 rgb(0 0 0 / 0.05);
  --shadow-md: 0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1);
  --shadow-lg: 0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1);
  --shadow-xl: 0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1);
  --radius-sm: 6px;
  --radius-md: 8px;
  --radius-lg: 12px;
  --radius-xl: 16px;
  --transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
}

.app {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background: linear-gradient(135deg, var(--background) 0%, var(--neutral-100) 100%);
  font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  color: var(--text-primary);
  width: 100%;
  position: relative;
  overflow-x: hidden;
}

.app::before {
  content: '';
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: 
    radial-gradient(circle at 20% 80%, rgba(59, 130, 246, 0.08) 0%, transparent 50%),
    radial-gradient(circle at 80% 20%, rgba(139, 92, 246, 0.08) 0%, transparent 50%),
    radial-gradient(circle at 40% 40%, rgba(16, 185, 129, 0.04) 0%, transparent 50%);
  pointer-events: none;
  z-index: 0;
}

.app-header {
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(20px);
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
  z-index: 100;
  position: relative;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 32px;
  height: 72px;
  max-width: 1400px;
  margin: 0 auto;
}

.app-title {
  margin: 0;
  color: var(--text-primary);
  font-size: 24px;
  font-weight: 700;
  background: linear-gradient(135deg, var(--primary-color), #8b5cf6);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.app-nav {
  display: flex;
  gap: 4px;
  background: var(--surface-hover);
  padding: 4px;
  border-radius: var(--radius-lg);
  border: 1px solid var(--border);
}

.nav-btn {
  padding: 14px 28px;
  border: 2px solid transparent;
  background: rgba(255, 255, 255, 0.8);
  color: var(--text-secondary);
  border-radius: var(--radius-lg);
  cursor: pointer;
  font-size: 16px;
  font-weight: 600;
  transition: all var(--transition);
  position: relative;
  overflow: hidden;
  backdrop-filter: blur(10px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  min-width: 140px;
  text-align: center;
}

.nav-btn::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(135deg, var(--primary-color), var(--accent-500));
  opacity: 0;
  transition: all var(--transition);
  border-radius: var(--radius-lg);
}

.nav-btn:hover:not(:disabled) {
  color: var(--primary-color);
  transform: translateY(-2px);
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
  border-color: var(--primary-200);
}

.nav-btn:hover:not(:disabled)::before {
  opacity: 0.1;
}

.nav-btn.active {
  background: linear-gradient(135deg, var(--primary-color), var(--accent-500));
  color: white;
  box-shadow: 0 8px 20px rgba(59, 130, 246, 0.3);
  transform: translateY(-3px);
  font-weight: 700;
  border: 2px solid rgba(255, 255, 255, 0.2);
}

.nav-btn.active::before {
  opacity: 0;
}

.nav-btn.active:hover {
  background: linear-gradient(135deg, var(--primary-hover), var(--accent-600));
  transform: translateY(-4px);
  box-shadow: 0 12px 24px rgba(59, 130, 246, 0.4);
}

.nav-btn:disabled {
  opacity: 0.4;
  cursor: not-allowed;
  transform: none;
  background: rgba(148, 163, 184, 0.1);
  color: var(--text-muted);
}

.app-main {
  flex: 1;
  overflow: hidden;
  max-width: 1400px;
  margin: 0 auto;
  width: 100%;
  padding: var(--space-8);
  display: flex;
  flex-direction: column;
  position: relative;
  z-index: 1;
}

.view-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  animation: fadeIn 0.3s ease-out;
  min-height: 0;
}

.upload-view-content {
  width: 100%;
  max-width: 1000px;
  display: flex;
  flex-direction: column;
  gap: 24px;
  margin: 0 auto;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.view-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: var(--space-8) 0;
  background: transparent;
  border-bottom: 1px solid rgba(226, 232, 240, 0.5);
  margin-bottom: var(--space-6);
  width: 100%;
  position: relative;
}

.view-header::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 1px;
  background: linear-gradient(90deg, transparent, var(--primary-200), transparent);
}

.view-header h2 {
  margin: 0;
  color: var(--text-primary);
  font-size: 36px;
  font-weight: 800;
  display: flex;
  align-items: center;
  gap: 16px;
  background: linear-gradient(135deg, var(--text-primary), var(--primary-600));
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.view-header h2::before {
  content: '';
  width: 4px;
  height: 28px;
  background: linear-gradient(135deg, var(--primary-color), #8b5cf6);
  border-radius: 2px;
}

.file-stats {
  display: flex;
  gap: 24px;
  font-size: 16px;
  color: var(--text-secondary);
  font-weight: 600;
  background: var(--surface);
  padding: 16px 24px;
  border-radius: var(--radius-lg);
  border: 2px solid var(--border);
  box-shadow: var(--shadow-md);
  text-shadow: 0 1px 1px rgba(0, 0, 0, 0.05);
}

.file-info {
  display: flex;
  gap: 24px;
  font-size: 14px;
  color: var(--text-secondary);
  background: var(--surface);
  padding: 12px 20px;
  border-radius: var(--radius-lg);
  border: 1px solid var(--border);
  box-shadow: var(--shadow-sm);
}

.view-content {
  flex: 1;
  display: flex;
  overflow: hidden;
  gap: 24px;
}

.content-main {
  flex: 1;
  overflow: hidden;
  background: var(--surface);
  border-radius: var(--radius-xl);
  box-shadow: var(--shadow-md);
  border: 1px solid var(--border);
}

.content-sidebar {
  width: 420px;
  background: var(--surface);
  border-radius: var(--radius-xl);
  box-shadow: var(--shadow-md);
  border: 1px solid var(--border);
  overflow-y: auto;
  animation: slideInRight 0.3s ease-out;
}

@keyframes slideInRight {
  from {
    opacity: 0;
    transform: translateX(20px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

.chart-panel {
  padding: 24px;
}

.chart-panel h3 {
  margin: 0 0 20px 0;
  color: var(--text-primary);
  font-size: 18px;
  font-weight: 600;
}

.app-footer {
  background: var(--surface);
  border-top: 1px solid var(--border);
  padding: 16px 32px;
  margin-top: 24px;
  max-width: 1400px;
  margin-left: auto;
  margin-right: auto;
}

.footer-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 13px;
  color: var(--text-muted);
}

.error {
  color: var(--error-color);
  background: #fef2f2;
  padding: 8px 12px;
  border-radius: var(--radius-sm);
  border: 1px solid #fecaca;
}

/* 工具函数样式 */
.format-file-size {
  font-family: 'JetBrains Mono', 'Fira Code', monospace;
  font-size: 13px;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .app-main {
    padding: 0 24px;
  }
  
  .header-content {
    padding: 0 24px;
  }
  
  .content-sidebar {
    width: 360px;
  }
}

@media (max-width: 768px) {
  .header-content {
    flex-direction: column;
    height: auto;
    padding: 16px 20px;
    gap: 16px;
  }
  
  .app-title {
    font-size: 20px;
  }
  
  .app-nav {
    width: 100%;
    justify-content: center;
  }
  
  .app-main {
    padding: 0 20px;
  }
  
  .view-content {
    flex-direction: column;
  }
  
  .content-sidebar {
    width: 100%;
    border-left: none;
    border-top: 1px solid var(--border);
  }
  
  .view-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
  
  .file-stats,
  .file-info {
    flex-direction: column;
    gap: 8px;
  }
}

@media (max-width: 480px) {
  .app-main {
    padding: 0 16px;
  }
  
  .header-content {
    padding: 16px;
  }
  
  .view-header h2 {
    font-size: 24px;
  }
}

/* 滚动条样式 */
::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

::-webkit-scrollbar-track {
  background: var(--surface-hover);
  border-radius: 4px;
}

::-webkit-scrollbar-thumb {
  background: var(--border);
  border-radius: 4px;
  transition: var(--transition);
}

::-webkit-scrollbar-thumb:hover {
  background: var(--text-muted);
}

/* 选择文本样式 */
::selection {
  background: var(--primary-light);
  color: var(--primary-color);
}

/* 焦点样式 */
*:focus-visible {
  outline: 2px solid var(--primary-color);
  outline-offset: 2px;
}

/* 加载动画 */
@keyframes pulse {
  0%, 100% {
    opacity: 1;
  }
  50% {
    opacity: 0.5;
  }
}

.loading {
  animation: pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite;
}
</style>

<script lang="ts">
// 工具函数
function formatFileSize(bytes: number): string {
  if (bytes === 0) return '0 B';
  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}
</script>